/*
 AMENDMENTS:
 DATE          NAME        VERSION     DESCRIPTION
--------       -----       -------     -----------
 21/01/2009    KCF       	1.0.0       1.UpdateUsersAction.java : Add Update Users with Security Group.
*/
package com.mbbmap.security.action;

import java.util.ArrayList;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

//import com.eremit.app.cus.business.comparator.*;
//20071204 : Added by Michael
import com.mbbmap.app.EbppKeys;
import com.mbbmap.app.dao.SecGroupLevelDao;
import com.mbbmap.app.dao.SysLogDao;
import com.mbbmap.app.dao.UserDao;
import com.mbbmap.app.exception.LogonException;
import com.mbbmap.app.exception.UniqueKeyViolationException;
import com.mbbmap.app.home.ParamHome;
import com.mbbmap.app.home.SecAccessHome;
import com.mbbmap.app.home.SecGroupHome;
import com.mbbmap.app.home.SecUsersHome;
import com.mbbmap.app.home.SysLogHome;
import com.mbbmap.app.manager.ConfigManager;
import com.mbbmap.security.dao.SecGroupsDao;
import com.mbbmap.util.Constants;
import com.mbbmap.util.SecAccessHelper;
import com.mbbmap.util.*;



/**
 *
 */
public final class UpdateUsersAction extends CommonDispatchAction {

  final String moduleCode = Constants.MDL_SEC_USER;
  
  /**
   * Account list
   */
  public ActionForward init(ActionMapping mapping,
    ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession(false);
	System.out.println("UpdateUsersAction.java: init");

	//Logon User ID CSR_ROLE or User Assigned Group.
	String strUIDGroupCode ="";
	//String strEUIDGroupCode = (String) session.getAttribute(Constants.CSR_ROLE);
	String strEUIDGroupCode = (String) session.getAttribute(Constants.LOGON_USER_ROLE);
	System.out.println("UpdateUsersAction.java: init_0001 strEUIDGroupCode" + strEUIDGroupCode);

	ArrayList arlSecGroupList = new ArrayList();
	ArrayList secGroupLevelList = new ArrayList();

	String strESelectedGroupCode ="";
	String strEMerchant = (String) session.getAttribute(Constants.MERCHANT_KEY);
	Properties paramProp = (Properties) session.getAttribute(Constants.PROPERTIES_PARAMETER);
	String strMerchant = "";
	String strRegExp = "";

	if ((strEMerchant != null) && (!strEMerchant.equals(""))){
		//strMerchant= EncryptionHelper.decrypt(strEMerchant,ConfigManager.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE));
	    strMerchant= strEMerchant;
	}else{
		strMerchant = "";
		return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}
	if(!isTokenValid(request)){
		System.out.println("Token validation failed!");
		session.invalidate();
		return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}else{
		resetToken(request);
		System.out.println("Token validation passed!");
	}
	if ((strEUIDGroupCode != null) && (!strEUIDGroupCode.equals(""))){
		//strUIDGroupCode= EncryptionHelper.decrypt(strEUIDGroupCode,ConfigManager.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE));
	    strUIDGroupCode= strEUIDGroupCode;
	}else{
		strUIDGroupCode = "";
		return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}
	
	boolean accessAllow = SecAccessHelper.isAccessAllow(moduleCode, request);
	if (!accessAllow) {
        return mapping.findForward(Constants.KEY_ACTION_MAPPING_ERR);
    }
	
	if (paramProp == null) {
	    return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}

	System.out.println("UpdateUsersAction.java: init_0002 strUIDGroupCode" + strUIDGroupCode);

	arlSecGroupList = SecGroupHome.getInstance().findSecGroupList(strMerchant);

	if ((strEUIDGroupCode != null) && (!strEUIDGroupCode.equals(""))){
		secGroupLevelList = SecAccessHome.getInstance().findSecGroupLevelList(strMerchant,strUIDGroupCode);
		//This for loop is to get the Module Name of the Access Module.
		for(int i=0;i<secGroupLevelList.size();i++){
			//System.out.println("UpdateSecLevelAction.java: getGroup_002");
			SecGroupLevelDao secGrpLevelDao = (SecGroupLevelDao)secGroupLevelList.get(i);
			String tmpcGrpCode = "";
			tmpcGrpCode = secGrpLevelDao.getcGroupCode();
			//System.out.println("UpdateSecLevelAction.java: getGroup tmpcGrpCode" + tmpcGrpCode);
			if (tmpcGrpCode != null && !tmpcGrpCode.equals("")){
				for(int j=0;j<arlSecGroupList.size();j++){
					SecGroupsDao secgroupDao = (SecGroupsDao)arlSecGroupList.get(j);
					if (secgroupDao.getGroupCode().equals(tmpcGrpCode)){
						secGrpLevelDao.setChildGroupName(secgroupDao.getGroupName());
					}
				}
			}
		}
	}

	//strRegExp = PwdValidationParamHome.getInstance().getParam(Constants.PARAM_PASSWORD_REG_EXPR);
	strRegExp = paramProp.getProperty(ParamHome.TECH_PARAM_PASSWORD_REG_EXPR);
	
	session.setAttribute(Constants.PASSWORD_REG_EXP, strRegExp);

	session.setAttribute(Constants.SECURITY_UGROUP, secGroupLevelList);
	session.setAttribute(Constants.SELECTED_SEC_UGRP, strESelectedGroupCode);
	session.setAttribute(Constants.LOGON_ERR_MSG, "");
    return mapping.findForward(Constants.KEY_ACTION_SUCCESS);
  }
  
  /**
   * Edit users
   */
  public ActionForward editUsers(ActionMapping mapping,
    ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws Exception {

    final String PROG_ID="UpdateUsersAction.editUsers";
    HttpSession session = request.getSession(false);
	System.out.println("UpdateUsersAction.java: editUsers");
	String strEMerchant = (String) session.getAttribute(Constants.MERCHANT_KEY);
	String strMerchant = "";
	String currLogonUserId= (String) session.getAttribute(Constants.LOGINID);

	if ((strEMerchant != null) && (!strEMerchant.equals(""))){
		//strMerchant= EncryptionHelper.decrypt(strEMerchant,ConfigManager.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE));
	    strMerchant = strEMerchant;
	}else{
		strMerchant = "";
		return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}
	if(!isTokenValid(request)){
		System.out.println("Token validation failed!");
		session.invalidate();
		return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}else{
		resetToken(request);
		System.out.println("Token validation passed!");
	}
	
	if ( (currLogonUserId == null) || (currLogonUserId.equals("")) ){
	    return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}
	
	boolean accessAllow = SecAccessHelper.isAccessAllow(moduleCode, request);
	if (!accessAllow) {
        return mapping.findForward(Constants.KEY_ACTION_MAPPING_ERR);
    }

	String roleCode =(String) session.getAttribute(Constants.LOGON_USER_ROLE);
	if (roleCode == null || roleCode.trim().equals("")) {
	    return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}

	ArrayList secGroupUserList = new ArrayList();
	String strSelectedGroupCode ="";
	String strESelectedGroupCode = (String) session.getAttribute(Constants.SELECTED_SEC_UGRP);
	String strUserID = sanitize(request.getParameter("sremuser"));
	System.out.println("UpdateUsersAction.java: editUsers_002 strUserID " + strUserID);

	String strErrLogonMsg = "";
	SysLogDao sysLogDao = new SysLogDao();

    try{
    	if ((strESelectedGroupCode != null) && (!strESelectedGroupCode.equals(""))){
			strSelectedGroupCode= sanitize(EncryptionHelper.decrypt(strESelectedGroupCode,ConfigManager.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE)));
			secGroupUserList = SecUsersHome.getInstance().findSecGroupUserList(strUserID,strMerchant,strSelectedGroupCode);
		}
		
		if (secGroupUserList.size()<1) {
		    strErrLogonMsg = ConfigManager.getInstance().get(Constants.MSG_LOGON_ERR_INVALID_USER);
		}
		
		System.out.println("UpdateUsersAction.java: editUsers_004 strSelectedGroupCode " + strSelectedGroupCode);
		System.out.println("UpdateUsersAction.java: editUsers_005 secGroupUserList.size()" + secGroupUserList.size());
		
		if (secGroupUserList.size()>1) {
		    strErrLogonMsg = "This User ID has more than one user!";
		    System.out.println("This User ID has more than one user!");
		}

		session.setAttribute(Constants.SELECTED_SEC_UGRP, strESelectedGroupCode);
		session.setAttribute(Constants.SECURITY_USER_LIST, secGroupUserList);
		session.setAttribute(Constants.LOGON_ERR_MSG, strErrLogonMsg);

	}catch (Exception e1) {
		System.out.println("Exception: " + e1.toString());
		//sysLogDao.setStatus(Constants.ACT_STATUS_FAIL_GENERAL);
		//sysLogDao.setUserField2(e1.getMessage());
		//SysLogHome.getInstance().insertSysLog(sysLogDao);

		return mapping.findForward("error");
	}catch (Throwable e2) {
		System.out.println("Export error: " + e2.toString());
		//sysLogDao.setStatus(Constants.ACT_STATUS_FAIL_GENERAL);
		//sysLogDao.setUserField2(e2.getMessage());
		//SysLogHome.getInstance().insertSysLog(sysLogDao);

		return mapping.findForward("error");
	}
    return mapping.findForward(Constants.SCOPE_EDIT_USER);
  }
	  
  /**
   * Account list
   */
  public ActionForward getUsers(ActionMapping mapping,
    ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession(false);
	System.out.println("UpdateUsersAction.java: getUsers");
	String strEMerchant = (String) session.getAttribute(Constants.MERCHANT_KEY);
	String strMerchant = "";

	if ((strEMerchant != null) && (!strEMerchant.equals(""))){
		//strMerchant= EncryptionHelper.decrypt(strEMerchant,ConfigManager.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE));
	    strMerchant= strEMerchant;
	}else{
		strMerchant = "";
		return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}
	if(!isTokenValid(request)){
		System.out.println("Token validation failed!");
		session.invalidate();
		return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}else{
		resetToken(request);
		System.out.println("Token validation passed!");
	}

	boolean accessAllow = SecAccessHelper.isAccessAllow(moduleCode, request);
	if (!accessAllow) {
        return mapping.findForward(Constants.KEY_ACTION_MAPPING_ERR);
    }

	ArrayList secGroupUserList = new ArrayList();
	String strSelectedGroupCode ="";
	String strESelectedGroupCode = request.getParameter("selusergrp");
	if ((strESelectedGroupCode != null) && (!strESelectedGroupCode.equals(""))){
		strSelectedGroupCode= sanitize(EncryptionHelper.decrypt(strESelectedGroupCode,ConfigManager.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE)));
		secGroupUserList = SecUsersHome.getInstance().findSecGroupUserList(strMerchant,strSelectedGroupCode);
	}
	System.out.println("UpdateUsersAction.java: getUsers_001 secGroupUserList.size()" + secGroupUserList.size());
	//SQL COMMAND select a.logonid from bguser a inner join (property b inner join propertydefinition c on (b.idx = c.idx) and (c.uname = 'CSR_ROLE') and (b.value = 'SADMIN')) on a.id = b.id
	session.setAttribute(Constants.SELECTED_SEC_UGRP, strESelectedGroupCode);
	session.setAttribute(Constants.SECURITY_USER_LIST, secGroupUserList);
	session.setAttribute(Constants.LOGON_ERR_MSG, "");
    return mapping.findForward(Constants.KEY_ACTION_SUCCESS);
  }


  /**
   * Account list
   */
  public ActionForward addUsers(ActionMapping mapping,
    ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws Exception {

    final String PROG_ID="UpdateUsersAction.addUsers";
    HttpSession session = request.getSession(false);
	System.out.println("UpdateUsersAction.java: addUsers");
	String strEMerchant = (String) session.getAttribute(Constants.MERCHANT_KEY);
	String strMerchant = "";
	String currLogonUserId= (String) session.getAttribute(Constants.LOGINID);

	if ((strEMerchant != null) && (!strEMerchant.equals(""))){
		//strMerchant= EncryptionHelper.decrypt(strEMerchant,ConfigManager.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE));
	    strMerchant= strEMerchant;
	}else{
		strMerchant = "";
		return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}
	if(!isTokenValid(request)){
		System.out.println("Token validation failed!");
		session.invalidate();
		return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}else{
		resetToken(request);
		System.out.println("Token validation passed!");
	}
	
	if ( (currLogonUserId == null) || (currLogonUserId.equals("")) ){
	    return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}
	
	boolean accessAllow = SecAccessHelper.isAccessAllow(moduleCode, request);
	if (!accessAllow) {
        return mapping.findForward(Constants.KEY_ACTION_MAPPING_ERR);
    }

	String roleCode =(String) session.getAttribute(Constants.LOGON_USER_ROLE);
	if (roleCode == null || roleCode.trim().equals("")) {
	    return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}
	
	ArrayList secGroupUserList = new ArrayList();
	String strSelectedGroupCode ="";
	String validIDFlag ="";
	String passwordResetFlag ="";
	String strESelectedGroupCode = request.getParameter("selusergrp");
	String strUserID = sanitize(request.getParameter("UserID"));
	String strUserName = sanitize(request.getParameter("UserName"));
	String strFullName = sanitize(request.getParameter("FullName"));
	String strEmail = sanitize(request.getParameter("Email"));
	String strUserDept = sanitize(request.getParameter("UserDept"));
	String strUserRegion = sanitize(request.getParameter("UserRegion"));
	String strUserCountryCode = sanitize(request.getParameter("UserRegion"));
	System.out.println("UpdateUsersAction.java: addUsers_002 strUserID " + strUserID);
	String strUserPWD = sanitizePwd(request.getParameter("UserPWD"));
	System.out.println("UpdateUsersAction.java: addUsers_003 strUserPWD " + strUserPWD);

	String strErrLogonMsg = "";
	long userDBId = -1;
	
	SysLogDao sysLogDao = new SysLogDao();

    try{
		//PersistServer.activate(Constants.MERCHANT);
		//PersistServer.beginTransaction();


		if ((strESelectedGroupCode != null) && (!strESelectedGroupCode.equals(""))){
			strSelectedGroupCode= sanitize(EncryptionHelper.decrypt(strESelectedGroupCode,ConfigManager.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE)));
			System.out.println("UpdateUsersAction.java: addUsers_003A strUserPWD " + strUserPWD);

			//validIDFlag = SecUsersHome.getInstance().findExistChecklist(strMerchant, strUserID);
			
			//passwordResetFlag = PwdValidationParamHome.getInstance().getParam(Constants.PARAM_PASSWORD_RESET_FLAG);

			UserDao user = new UserDao();
			user.setUserLogin(strUserID);
			user.setUserName(strUserName);
			user.setFullName(strFullName);
			user.setEmail(strEmail);
			user.setUserDept(strUserDept);
			user.setUserRegion(strUserRegion);
			user.setCountryCode(strUserCountryCode);
			user.setLoginPassword(strUserPWD);
			user.setUserRole(strSelectedGroupCode);
			user.setUserEnabled(Constants.DB_YES);

			// Activity log
			sysLogDao.setActivityCode(Constants.ACT_CODE_SECURITY);
			sysLogDao.setAcctID(strMerchant);
			sysLogDao.setActivityName(PROG_ID);
			sysLogDao.setUserID(currLogonUserId);
			sysLogDao.setRole(roleCode);
			sysLogDao.setUserField1("Selected Group=" + strSelectedGroupCode + ", Add User: "+ strUserID);
	    	
			userDBId = SecUsersHome.getInstance().createUser(user, strMerchant, currLogonUserId);
			if (userDBId > 0) {
			    sysLogDao.setStatus(Constants.ACT_STATUS_SUCCESS);
			}
			SysLogHome.getInstance().insertSysLog(sysLogDao);

			System.out.println("UpdateUsersAction.java: addUsers_003B strUserPWD " + strUserPWD);
		}

		if ((strSelectedGroupCode != null) && (!strSelectedGroupCode.equals(""))){
			secGroupUserList = SecUsersHome.getInstance().findSecGroupUserList(strMerchant,strSelectedGroupCode);
		}

		System.out.println("UpdateUsersAction.java: addUsers_004 strSelectedGroupCode " + strSelectedGroupCode);
		System.out.println("UpdateUsersAction.java: addUsers_005 secGroupUserList.size()" + secGroupUserList.size());
		session.setAttribute(Constants.SELECTED_SEC_UGRP, strESelectedGroupCode);
		session.setAttribute(Constants.SECURITY_USER_LIST, secGroupUserList);
		session.setAttribute(Constants.LOGON_ERR_MSG, strErrLogonMsg);

    } catch (LogonException le) {
	    if (le.getErrorCode() == LogonException.USER_ID_PWD_SAME) {
	        strErrLogonMsg = ConfigManager.getInstance().get(Constants.MSG_CHANGEPWD_PWD_SAME_USER_ID);
	    }
	}catch (UniqueKeyViolationException ukve) {
		System.out.println("Exception: " + ukve.toString());
		
		strErrLogonMsg = ConfigManager.getInstance().get(Constants.MSG_ADD_USER_LOGIN_ID_ALREADY_EXIST);
		sysLogDao.setStatus(Constants.ACT_STATUS_FAIL_GENERAL);
		sysLogDao.setUserField2(strErrLogonMsg);
		SysLogHome.getInstance().insertSysLog(sysLogDao);
		session.setAttribute(Constants.LOGON_ERR_MSG, strErrLogonMsg);
		return mapping.findForward(Constants.KEY_ACTION_SUCCESS);
	}catch (Exception e) {
		System.out.println("Export error: " + e.toString());
		sysLogDao.setStatus(Constants.ACT_STATUS_FAIL_GENERAL);
		sysLogDao.setUserField2(e.getMessage());
		SysLogHome.getInstance().insertSysLog(sysLogDao);

		return mapping.findForward("error");
	}catch (Throwable e2) {
		System.out.println("Export error: " + e2.toString());
		sysLogDao.setStatus(Constants.ACT_STATUS_FAIL_GENERAL);
		sysLogDao.setUserField2(e2.getMessage());
		SysLogHome.getInstance().insertSysLog(sysLogDao);

		return mapping.findForward("error");
	}
	
    return mapping.findForward(Constants.KEY_ACTION_SUCCESS);
  }

  /**
   * Account list
   */
  public ActionForward remUsers(ActionMapping mapping,
    ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws Exception {

    final String PROG_ID="UpdateUsersAction.remUsers";
    HttpSession session = request.getSession(false);
	System.out.println("UpdateUsersAction.java: remUsers");
	String strEMerchant = (String) session.getAttribute(Constants.MERCHANT_KEY);
	String strMerchant = "";
	String currLogonUserId= (String) session.getAttribute(Constants.LOGINID);

	if ((strEMerchant != null) && (!strEMerchant.equals(""))){
		//strMerchant= EncryptionHelper.decrypt(strEMerchant,ConfigManager.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE));
	    strMerchant = strEMerchant;
	}else{
		strMerchant = "";
		return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}
	if(!isTokenValid(request)){
		System.out.println("Token validation failed!");
		session.invalidate();
		return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}else{
		resetToken(request);
		System.out.println("Token validation passed!");
	}
	
	if ( (currLogonUserId == null) || (currLogonUserId.equals("")) ){
	    return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}
	
	boolean accessAllow = SecAccessHelper.isAccessAllow(moduleCode, request);
	if (!accessAllow) {
        return mapping.findForward(Constants.KEY_ACTION_MAPPING_ERR);
    }

	String roleCode =(String) session.getAttribute(Constants.LOGON_USER_ROLE);
	if (roleCode == null || roleCode.trim().equals("")) {
	    return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}

	
	ArrayList secGroupUserList = new ArrayList();
	String strSelectedGroupCode ="";
	String strESelectedGroupCode = (String) session.getAttribute(Constants.SELECTED_SEC_UGRP);
	String strUserID = sanitize(request.getParameter("sremuser"));
	System.out.println("UpdateUsersAction.java: remUsers_002 strUserID " + strUserID);

	String strErrLogonMsg = "";
	SysLogDao sysLogDao = new SysLogDao();

    try{
		//PersistServer.activate(Constants.MERCHANT);
		//PersistServer.beginTransaction();
        boolean removeSuccess = false;


		if ((strESelectedGroupCode != null) && (!strESelectedGroupCode.equals(""))){
			strSelectedGroupCode= sanitize(EncryptionHelper.decrypt(strESelectedGroupCode,ConfigManager.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE)));

			// Activity log
			sysLogDao.setActivityCode(Constants.ACT_CODE_SECURITY);
			sysLogDao.setAcctID(strMerchant);
			sysLogDao.setActivityName(PROG_ID);
			sysLogDao.setUserID(currLogonUserId);
			sysLogDao.setRole(roleCode);
			sysLogDao.setUserField1("Selected Group = " + strSelectedGroupCode + ", Merchant=" + strMerchant + ", Remove User Id="+strUserID);
			
			//SecurityHelper.removeUser(strUserID);
			removeSuccess = SecUsersHome.getInstance().removeUser(strUserID, strMerchant, currLogonUserId);
			if (removeSuccess) {
			    sysLogDao.setStatus(Constants.ACT_STATUS_SUCCESS);
			} else {
			    sysLogDao.setStatus(Constants.ACT_STATUS_FAIL_GENERAL);
			}
			
			SysLogHome.getInstance().insertSysLog(sysLogDao);

		}

		//PersistServer.commitTransaction();

		if ((strSelectedGroupCode != null) && (!strSelectedGroupCode.equals(""))){
			secGroupUserList = SecUsersHome.getInstance().findSecGroupUserList(strMerchant,strSelectedGroupCode);
		}
		
		if (!removeSuccess) {
		    strErrLogonMsg = ConfigManager.getInstance().get(Constants.MSG_USER_DELETE_FAIL);
		}

		System.out.println("UpdateUsersAction.java: remUsers_004 strSelectedGroupCode " + strSelectedGroupCode);
		System.out.println("UpdateUsersAction.java: remUsers_005 secGroupUserList.size()" + secGroupUserList.size());

		if (!strErrLogonMsg.equals(""))
		    sysLogDao.setUserField2(strErrLogonMsg);
		

		session.setAttribute(Constants.SELECTED_SEC_UGRP, strESelectedGroupCode);
		session.setAttribute(Constants.SECURITY_USER_LIST, secGroupUserList);
		session.setAttribute(Constants.LOGON_ERR_MSG, strErrLogonMsg);

	}catch (Exception e1) {
		System.out.println("Exception: " + e1.toString());
		sysLogDao.setStatus(Constants.ACT_STATUS_FAIL_GENERAL);
		sysLogDao.setUserField2(e1.getMessage());
		SysLogHome.getInstance().insertSysLog(sysLogDao);

		return mapping.findForward("error");
	}catch (Throwable e2) {
		System.out.println("Export error: " + e2.toString());
		sysLogDao.setStatus(Constants.ACT_STATUS_FAIL_GENERAL);
		sysLogDao.setUserField2(e2.getMessage());
		SysLogHome.getInstance().insertSysLog(sysLogDao);

		return mapping.findForward("error");
	}
	//finally {
		//PersistServer.deactivate();
	//}
    return mapping.findForward(Constants.KEY_ACTION_SUCCESS);
  }
  
  /**
   * Update edited user
   */
  public ActionForward updateUsers(ActionMapping mapping,
    ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws Exception {

    final String PROG_ID="UpdateUsersAction.updateUsers";
    HttpSession session = request.getSession(false);
	System.out.println("UpdateUsersAction.java: updateUsers");
	String strEMerchant = (String) session.getAttribute(Constants.MERCHANT_KEY);
	String strMerchant = "";
	String currLogonUserId= (String) session.getAttribute(Constants.LOGINID);

	if ((strEMerchant != null) && (!strEMerchant.equals(""))){
		//strMerchant= EncryptionHelper.decrypt(strEMerchant,ConfigManager.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE));
	    strMerchant = strEMerchant;
	}else{
		strMerchant = "";
		return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}
	if(!isTokenValid(request)){
		System.out.println("Token validation failed!");
		session.invalidate();
		return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}else{
		resetToken(request);
		System.out.println("Token validation passed!");
	}
	
	if ( (currLogonUserId == null) || (currLogonUserId.equals("")) ){
	    return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}
	
	boolean accessAllow = SecAccessHelper.isAccessAllow(moduleCode, request);
	if (!accessAllow) {
        return mapping.findForward(Constants.KEY_ACTION_MAPPING_ERR);
    }

	String roleCode =(String) session.getAttribute(Constants.LOGON_USER_ROLE);
	if (roleCode == null || roleCode.trim().equals("")) {
	    return mapping.findForward(Constants.KEY_ACTION_SESSION_ERR);
	}

	ArrayList secGroupUserList = new ArrayList();
	String strSelectedGroupCode ="";
	String strESelectedGroupCode = (String) session.getAttribute(Constants.SELECTED_SEC_UGRP);
	String strUserID = sanitize(request.getParameter("sremuser"));
	String strUserName = sanitize(request.getParameter("UserName"));
	String strFullName = sanitize(request.getParameter("FullName"));
	String strEmail = sanitize(request.getParameter("Email"));
	String strUserDept = sanitize(request.getParameter("UserDept"));
	String strUserRegion = sanitize(request.getParameter("UserRegion"));
	String strUserCountryCode = sanitize(request.getParameter("UserRegion"));
	 
	System.out.println("UpdateUsersAction.java: updateUsers_002 strUserID " + strUserID);

	String strErrLogonMsg = "";
	SysLogDao sysLogDao = new SysLogDao();

    try{
        boolean updateSuccess = false;

        UserDao user = new UserDao();
//		user.setUserLogin(strUserID);
		user.setUserName(strUserName);
		user.setFullName(strFullName);
		user.setEmail(strEmail);
		user.setUserDept(strUserDept);
		user.setUserRegion(strUserRegion);
		user.setCountryCode(strUserCountryCode);
		
		if ((strESelectedGroupCode != null) && (!strESelectedGroupCode.equals(""))){
			strSelectedGroupCode= sanitize(EncryptionHelper.decrypt(strESelectedGroupCode,ConfigManager.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE)));

			// Activity log
			sysLogDao.setActivityCode(Constants.ACT_CODE_SECURITY);
			sysLogDao.setAcctID(strMerchant);
			sysLogDao.setActivityName(PROG_ID);
			sysLogDao.setUserID(currLogonUserId);
			sysLogDao.setRole(roleCode);
			sysLogDao.setUserField1("Selected Group=" + strSelectedGroupCode + ",Merchant=" + strMerchant + ",Edited User Id="+strUserID);
			
			updateSuccess = SecUsersHome.getInstance().updateUser(user,strUserID, strMerchant, currLogonUserId);
			if (updateSuccess) {
			    sysLogDao.setStatus(Constants.ACT_STATUS_SUCCESS);
			} else {
			    sysLogDao.setStatus(Constants.ACT_STATUS_FAIL_GENERAL);
			}
		}

		if ((strSelectedGroupCode != null) && (!strSelectedGroupCode.equals(""))){
			secGroupUserList = SecUsersHome.getInstance().findSecGroupUserList(strMerchant,strSelectedGroupCode);
		}
		
		if (!updateSuccess) {
		    strErrLogonMsg = ConfigManager.getInstance().get(Constants.MSG_USER_EDIT_FAIL);
		}else{
			strErrLogonMsg = ConfigManager.getInstance().get(Constants.MSG_USER_EDIT_SUCCESS);
		}

		System.out.println("UpdateUsersAction.java: updateUsers_004 strSelectedGroupCode " + strSelectedGroupCode);
		System.out.println("UpdateUsersAction.java: updateUsers_005 secGroupUserList.size()" + secGroupUserList.size());

		if (!strErrLogonMsg.equals(""))
		    sysLogDao.setUserField2(strErrLogonMsg);
		
		SysLogHome.getInstance().insertSysLog(sysLogDao);
		session.setAttribute(Constants.SELECTED_SEC_UGRP, strESelectedGroupCode);
		session.setAttribute(Constants.SECURITY_USER_LIST, secGroupUserList);
		session.setAttribute(Constants.LOGON_ERR_MSG, strErrLogonMsg);

	}catch (Exception e1) {
		System.out.println("Exception: " + e1.toString());
		sysLogDao.setStatus(Constants.ACT_STATUS_FAIL_GENERAL);
		sysLogDao.setUserField2(e1.getMessage());
		SysLogHome.getInstance().insertSysLog(sysLogDao);

		return mapping.findForward("error");
	}catch (Throwable e2) {
		System.out.println("Export error: " + e2.toString());
		sysLogDao.setStatus(Constants.ACT_STATUS_FAIL_GENERAL);
		sysLogDao.setUserField2(e2.getMessage());
		SysLogHome.getInstance().insertSysLog(sysLogDao);

		return mapping.findForward("error");
	}
    return mapping.findForward(Constants.KEY_ACTION_SUCCESS);
  }
}
